/**
 * 拦截器验证token
 */
import { Injectable } from '@angular/core';
import {HttpInterceptor, HttpHandler, HttpRequest, HttpEvent,} from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable,  } from 'rxjs';
import { ApiList } from './apiList';
import {userApi} from "../../api/user";
import Cookies from 'js-cookie';

@Injectable()
export class InterceptorService implements HttpInterceptor {
    constructor( public router: Router,  public api: ApiList) {
    };
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let authReq: any;
        // 实现第一次不拦截的方式：1. 指定接口不拦截  2. 判断本地localStorage
        let whiteList = [userApi.login];
        const nowApi = req.url.replace(this.api.baseurl, '');
        if (whiteList.indexOf(nowApi) === -1) {
            if(Cookies.get('token')){
                const token = Cookies.get('token');
                authReq = req.clone({ headers: req.headers.set('Authorization', token || ''), withCredentials: true });
                return next.handle(authReq);
            }else{
                this.router.navigate(['/login']);
                authReq = req.clone({ withCredentials: true });
                return next.handle(authReq);
            }
        }else{
            authReq = req.clone({ withCredentials: true  });
            return next.handle(authReq);
        }
    }
}
